package com.jimei.voucher.service.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.jimei.common.ServerResponse;
import com.jimei.common.modules.Const;
import com.jimei.common.modules.PageBean;
import com.jimei.common.modules.SnowflakeIdWorker;
import com.jimei.voucher.config.RabbitConfig;
import com.jimei.voucher.dao.OrderMapper;
import com.jimei.voucher.exception.VoucherException;
import com.jimei.voucher.pojo.Order;
import com.jimei.voucher.service.OrderService;
import com.jimei.voucher.vo.OrderVO;


/**
 *
 * Service实现类
 *
 * @author jimei
 * @email 10832053@qq.com
 * @date 2018-09-07 11:02:58
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class.getSimpleName());

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
    * 通过pid获取对象
    * @param pid
    * @return
    */
    @Override
    public ServerResponse<OrderVO> selectByPid(String pid) {
        Order order = selectOrderByPid(pid);
        if(order == null){
            return ServerResponse.createByErrorMessage("请确认查询参数是否正确");
        }
        OrderVO vo = new OrderVO();
        order.toVO(vo);
        return ServerResponse.createBySuccess(vo);
    }


    private Order selectOrderByPid(String pid) {
        Order order = orderMapper.selectByPid(pid);
        return order;
    }

    /**
     * 按照条件获取数据
     * params中需包含sort（需要排序字段），order（排序方式 desc，asc等）
     * @param params
     * @return
     */
    @Override
    public ServerResponse<PageBean<OrderVO>> selectListByParams(Map<String,Object> params) {
        //设置分页条件
        int page = 0;
        int pageSize = Const.DEFAULT_PAGE_SIZE;
        Object pageParams = params.get("page");
        Object pageSizeParams = params.get("pageSize");

        if(pageParams != null){
            page = Integer.valueOf(pageParams.toString());
        }
        if(pageSizeParams != null){
            pageSize = Integer.valueOf(pageSizeParams.toString());
        }
        PageHelper.startPage(page, pageSize);
        List<OrderVO> sourceList = orderMapper.selectListByParams(params);
        PageBean<OrderVO> pageResult = new PageBean<>(sourceList);
        return ServerResponse.createBySuccess(pageResult);
    }

    /**
     * 新增方法
     * @return
     */
    @Override
    public ServerResponse<String> add(OrderVO orderVo) {
        Order order = new Order();
        order.fromVO(orderVo);
        //设置pid
        order.setPid(SnowflakeIdWorker.getInstance(0,0).nextId() + "");
        int addRowCount = orderMapper.insertSelective(order);
        if(addRowCount <= 0){
            throw new VoucherException("失败");
        }
        sendRabbit(order);
        return ServerResponse.createBySuccessMessage("成功");
    }

    /**
     * 修改方法
     * @return
     */
    @Override
    public int update(OrderVO orderVo) {
        Order order = new Order();
        order.fromVO(orderVo);
        return orderMapper.updateByPidSelective(order);
    }

    /**
     * 删除方法
     * @return
     */
    @Override
    public ServerResponse<String> deleteByPids(List<String> pids) {
        int deleteRowCount = orderMapper.deleteByPidSelective(pids);
        if(deleteRowCount <= 0){
            throw new VoucherException("删除失败");
        }
        return ServerResponse.createBySuccessMessage("删除成功");
    }

    /**
     * 取消订单
     */
    @Override
    public void cancelByPid(String pid) throws Exception {
        Order order = selectOrderByPid(pid);
        if(order == null) {
            logger.warn("订单{}不存在", pid);
            return;
        }
        int row = orderMapper.cancelByPid(pid);
        if(row > 0) {
            logger.info("订单取消{}", order);
        }
    }

    /**
     * 记录订单
     * @param order
     */
    private void sendRabbit(Order order) {
        MessageProperties properties = MessagePropertiesBuilder.newInstance().setExpiration("600000").build();//10分钟过期
        Message message = rabbitTemplate.getMessageConverter().toMessage(order.getPid(), properties);
        rabbitTemplate.send(RabbitConfig.ORDER_EXCHANGE, RabbitConfig.DIRECT_ORDER, message);
    }
}
